"""
自定义图表数据处理
"""
from utils import dispatch
from rest_framework import serializers


class ChartSerializer(serializers.Serializer):
    """图表序列化器
    reverse  正序  True逆序(大的在前)
    sort     是否排序
    type     1数组对象 2对象数组
    """
    chart_reverse = serializers.BooleanField(allow_null=True)
    chart_sort = serializers.BooleanField(allow_null=True)
    chart_type = serializers.CharField(allow_null=True, allow_blank=True, default='1')


class Chart:
    def __init__(self, request):
        """
        :param request:
        """
        serializer = ChartSerializer(data=request.GET)
        serializer.is_valid(raise_exception=True)
        self.sort = serializer.data.get('chart_sort') or False
        self.reverse = serializer.data.get('chart_reverse') or False
        self.type = serializer.data.get('chart_type') or '1'

    def get_data(self, query_set_result, name_col, value_col, dict_key=''):
        """
        :param query_set_result: query_set_result
        :param name_col: name对应属性
        :param value_col: value对应属性
        :param dict_key: 数据字典key
        """
        if self.type == '2':
            return self.get_bar_data(query_set_result, name_col, value_col, dict_key)
        return self.get_pi_data(query_set_result, name_col, value_col, dict_key)

    def get_pi_data(self, query_set_result, name_col, value_col, dict_key):
        """组织数组对象数据格式
        :return: [{'name': '', 'value': ''}, {'name': '', 'value': ''}]
        """
        query_data = dict()
        result = []
        total_value = 0
        for i in query_set_result:
            query_data[i.get(name_col)] = i.get(value_col)
            total_value += i.get(value_col)

        if not dict_key:
            for k, v in query_data.items():
                percent = '{:.0%}'.format(v / total_value if total_value else 0)
                result.append({'id': '', 'value': v, 'name': k, 'percent': percent})
        else:
            dict_data = dispatch.get_dictionary_config().get(dict_key, dict()).get('children', [])
            for i in dict_data:
                dict_id = i.get('value')
                data = {'id': dict_id, 'value': 0, 'name': i.get('label'), 'percent': '0%'}
                if dict_id in query_data:
                    data['value'] = query_data[dict_id]
                    data['percent'] = '{:.0%}'.format(data['value'] / total_value if total_value else 0)
                result.append(data)
        if self.sort:
            result.sort(key=lambda x: x['value'], reverse=self.reverse)
        return result

    def get_bar_data(self, query_set_result, name_col, value_col, dict_key):
        """组织对象数据格式
        :return: {'name': [], 'value': []}
        """
        result = self.get_pi_data(query_set_result, name_col, value_col, dict_key)
        name = []
        value = []
        percent = []
        for i in result:
            name.append(i['name'])
            value.append(i['value'])
            percent.append(i['percent'])
        return {'name': name, 'value': value, 'percent': percent}
